package com.example.phoneaddress;

import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.IBinder;
import android.telephony.PhoneStateListener;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.widget.Toast;

import com.example.phoneaddress.util.DBUtils;

public class MyService extends Service {
    public static final String TAG="MainActivity";
    public MyService() {
    }

    @Override
    public void onCreate() {
        super.onCreate();
        //当服务创建的时候调用的方法
        Log.i(TAG, "创建服务");
        //监听来电，查询来电号码的归属地
        listenIncomingCall();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        //服务销毁的时候调用的方法
        Log.i(TAG, "服务销毁");
    }

    @Override
    public IBinder onBind(Intent intent) {
        // 绑定服务
        throw new UnsupportedOperationException("Not yet implemented");
    }
    private void listenIncomingCall() {
        //1-获取电话管理者对象
        TelephonyManager tm= (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
        //让tm对象监听电话状态
        //参数1-监听器对象，参数2-监听内容
        tm.listen(new PhoneStateListener(){
            public void onCallStateChanged(int state, String incomingNumber) {
                super.onCallStateChanged(state, incomingNumber);
                //state--电话状态
                // incomingNumber--来电号码
                switch (state){
                    case TelephonyManager.CALL_STATE_IDLE:
                        //空闲状态
                        Log.i(TAG, "空闲状态");
                        break;
                    case TelephonyManager.CALL_STATE_OFFHOOK:
                        //通话状态
                        Log.i(TAG, "通话状态");
                        break;
                    case TelephonyManager.CALL_STATE_RINGING:
                        //响铃状态
                        //获取来电号码

                        Log.i(TAG, "响铃状态"+incomingNumber);

                        //查询归属地
                        String address= DBUtils.searchAddress(getApplicationContext(),incomingNumber);
                        //显示
                        Toast.makeText(getApplicationContext(),address,Toast.LENGTH_LONG).show();
                        break;
                }
            }

        },PhoneStateListener.LISTEN_CALL_STATE);

    }

}
